package com.kingsystem.kingteachermarks_backend.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.kingsystem.kingteachermarks_backend.entity.WorkPerformance;
import com.kingsystem.kingteachermarks_backend.entity.WorkPerformanceAllocation;
import com.kingsystem.kingteachermarks_backend.entity.WorkPerformanceFiles;
import com.kingsystem.kingteachermarks_backend.mapper.WorkPerformanceAllocationMapper;
import com.kingsystem.kingteachermarks_backend.mapper.WorkPerformanceFilesMapper;
import com.kingsystem.kingteachermarks_backend.mapper.WorkPerformanceMapper;
import com.kingsystem.kingteachermarks_backend.service.IWorkPerformanceAllocationService;
import com.kingsystem.kingteachermarks_backend.service.IWorkPerformanceFilesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * <p>
 * 前端控制器java json字符串
 * </p>
 *
 * @author leiyue_yao
 * @since 2025-06-04
 */
@Controller
@RequestMapping("/workPerformance")
@CrossOrigin
public class WorkPerformanceController {

    @Autowired
    private WorkPerformanceMapper wpm;//用来存储业绩信息

    @Autowired
    private IWorkPerformanceAllocationService wpam;//用来存储分配人员信息

    @Autowired
    private IWorkPerformanceFilesService wpfm;

    @PostMapping("/addWorkPerformance")
    @ResponseBody
    @Transactional
    public String addWorkPerformance(@RequestParam("param") String param) {
        try {
            JSONObject jo = JSON.parseObject(param);

            //region 添加到业绩主表
            UUID uuid = UUID.randomUUID();
            WorkPerformance wp = new WorkPerformance();
            wp.setTableKey(uuid.toString());
            //region 获取日期
            Date date = jo.getDate("finish_time");
            Instant instant = date.toInstant();
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
            wp.setFinishTime(localDateTime);
            //endregion
            wp.setQuantifyTitle(jo.getString("quantify_title"));
            wp.setDictQuantifyId(jo.getJSONObject("selectedQuantifyItem").getString("tableKey"));
            wp.setComments(jo.getString("comments"));
            wp.setFlowStatusId("1");
            wp.setRecordUserId(jo.getString("userId"));
            wpm.insert(wp);
            //endregion

            //region 添加附件
            JSONArray fileList = jo.getJSONArray("fileList");
            List<WorkPerformanceFiles> li_wpf = new ArrayList<>();

            for (int i = 0; i < fileList.size(); i++) {
                JSONObject jof = fileList.getJSONObject(i);
                WorkPerformanceFiles wpf = new WorkPerformanceFiles();
                wpf.setTableKey(UUID.randomUUID().toString());
                wpf.setWorkPerformanceId(uuid.toString());
                wpf.setFileName(jof.getString("name"));
                wpf.setServerFileName(jof.getString("serverFileName"));
                li_wpf.add(wpf);
            }
            wpfm.saveBatch(li_wpf);
            //endregion

            //region 添加人员分数分配
            JSONArray users = jo.getJSONArray("users");
            JSONArray marks = jo.getJSONArray("marks");
            List<WorkPerformanceAllocation> li_wpa = new ArrayList<>();
            for (int i = 0; i < users.size(); i++) {
                JSONObject jou = users.getJSONObject(i);

                WorkPerformanceAllocation wpa = new WorkPerformanceAllocation();
                wpa.setTableKey(UUID.randomUUID().toString());
                wpa.setWorkPerformanceId(uuid.toString());
                wpa.setUserId(jou.getString("tableKey"));
                wpa.setMarks(marks.getBigDecimal(i));
                wpa.setSort(i);

                li_wpa.add(wpa);
            }
            wpam.saveBatch(li_wpa);
            //endregion

            return "success";
        } catch (Exception ex) {
            return ex.getMessage();
        }
    }


    @PostMapping("/editWorkPerformance")
    @ResponseBody
    @Transactional
    public String editWorkPerformance(@RequestParam("param") String param) {
        try {
            JSONObject jo = JSON.parseObject(param);

            //region 更新业绩主表
            String workPerformanceId = jo.getString("tableKey");
            WorkPerformance wp = new WorkPerformance();
            wp.setTableKey(workPerformanceId);
            //region 获取日期
            Date date = jo.getDate("finish_time");
            Instant instant = date.toInstant();
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
            wp.setFinishTime(localDateTime);
            //endregion
            wp.setQuantifyTitle(jo.getString("quantify_title"));
            wp.setDictQuantifyId(jo.getJSONObject("selectedQuantifyItem").getString("tableKey"));
            wp.setComments(jo.getString("comments"));
            wp.setFlowStatusId("1");
            wp.setRecordUserId(jo.getString("userId"));
            wpm.updateById(wp);
            //endregion

            //region 添加附件，先删除，后添加

            QueryWrapper<WorkPerformanceFiles> qw_file = new QueryWrapper<>();
            qw_file.eq("work_performance_id", workPerformanceId);
            wpfm.remove(qw_file);


            JSONArray fileList = jo.getJSONArray("fileList");
            List<WorkPerformanceFiles> li_wpf = new ArrayList<>();
            for (int i = 0; i < fileList.size(); i++) {
                JSONObject jof = fileList.getJSONObject(i);
                WorkPerformanceFiles wpf = new WorkPerformanceFiles();
                wpf.setTableKey(UUID.randomUUID().toString());
                wpf.setWorkPerformanceId(workPerformanceId);
                wpf.setFileName(jof.getString("name"));
                wpf.setServerFileName(jof.getString("serverFileName"));
                li_wpf.add(wpf);
            }
            wpfm.saveBatch(li_wpf);
            //endregion

            //region 添加人员分数分配，先删除后添加

            QueryWrapper<WorkPerformanceAllocation> qw_al = new QueryWrapper<>();
            qw_al.eq("work_performance_id", workPerformanceId);
            wpam.remove(qw_al);


            JSONArray users = jo.getJSONArray("users");
            JSONArray marks = jo.getJSONArray("marks");
            List<WorkPerformanceAllocation> li_wpa = new ArrayList<>();
            for (int i = 0; i < users.size(); i++) {
                JSONObject jou = users.getJSONObject(i);

                WorkPerformanceAllocation wpa = new WorkPerformanceAllocation();
                wpa.setTableKey(UUID.randomUUID().toString());
                wpa.setWorkPerformanceId(workPerformanceId);
                wpa.setUserId(jou.getString("tableKey"));
                wpa.setMarks(marks.getBigDecimal(i));
                wpa.setSort(i);

                li_wpa.add(wpa);
            }
            wpam.saveBatch(li_wpa);
            //endregion

            return "success";
        } catch (Exception ex) {
            return ex.getMessage();
        }
    }

    @PostMapping("/delWorkPerformance")
    @ResponseBody
    @Transactional
    public String delWorkPerformance(@RequestParam("workPerformanceId") String workPerformanceId) {
        try {
            QueryWrapper<WorkPerformance> qw_wp = new QueryWrapper<>();
            qw_wp.eq("tableKey", workPerformanceId);
            wpm.delete(qw_wp);

            QueryWrapper<WorkPerformanceFiles> qw_file = new QueryWrapper<>();
            qw_file.eq("work_performance_id", workPerformanceId);
            wpfm.remove(qw_file);

            QueryWrapper<WorkPerformanceAllocation> qw_al = new QueryWrapper<>();
            qw_al.eq("work_performance_id", workPerformanceId);
            wpam.remove(qw_al);

            return "success";
        } catch (Exception ex) {
            return ex.getMessage();
        }
    }
}
